import axios from "axios";
import { ElMessage } from "element-plus";

// 获取验证码接口
const http = axios.create({
  baseURL: "https:/v3pz.itndedu.com/v3pz/", // 修正基础URL格式
  timeout: 10000,
});

// 添加请求拦截器
http.interceptors.request.use(
  function (config) {
    console.log("Request URL:", config.baseURL + config.url); // 打印请求URL
    const token = localStorage.getItem("pz_token");
    const whiteUrlPatterns = ["/login", "/get/code", "/user/authentication"];
    const isWhiteUrl = whiteUrlPatterns.some((pattern) =>
      config.url?.endsWith(pattern)
    );
    if (token && !isWhiteUrl) {
      config.headers["x-token"] = token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
http.interceptors.response.use(
  function (response) {
    if (response.data.code === -1) {
      ElMessage.warning(response.data.message);
    }
    if (response.data.code === -2) {
      localStorage.removeItem("pz_token");
      localStorage.removeItem("pz_userInfo");
      localStorage.removeItem("pz_v3pz");
      window.location.href = window.location.origin;
    }
    return response;
  },
  function (error) {
    if (error.response) {
      if (error.response.status === 404) {
        ElMessage.error("请求的资源未找到，请检查API路径");
      } else {
        ElMessage.error(
          `请求失败: ${error.response.status} ${error.response.statusText}`
        );
      }
    } else if (error.request) {
      ElMessage.error("请求未收到响应");
    } else {
      ElMessage.error("请求发生错误");
    }
    return Promise.reject(error);
  }
);

export default http;
